package org.ns.summer.data.mybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 实现 mybatis mapper代理调用！，获取连接自动释放
 */
public class MybatisMapperInvokeProxy implements InvocationHandler {
    SqlSessionFactory sqlSessionFactory;
    Class<?> mapperClass;

    public MybatisMapperInvokeProxy(SqlSessionFactory sqlSessionFactory, Class<?> mapperClass) {
        this.sqlSessionFactory = sqlSessionFactory;
        this.mapperClass = mapperClass;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MybatisTransactionManage manage = MybatisTransactionManage.get();
        SqlSession sqlSession = null;
        if (manage != null) { // 如果开启类事务管理。
            sqlSession = manage.openSession(sqlSessionFactory);
        } else {
            sqlSession = sqlSessionFactory.openSession(true);
        }
        try {
            Object mapper = sqlSession.getMapper(mapperClass);
            return method.invoke(mapper, args);
        } catch (Throwable e) {
            throw e;
        } finally {
            if (manage == null) { // 没有开启事务则关闭session，如果开启类事务交给事务管理去协调
                sqlSession.close();
            }
        }
    }
}
